import re
import sys
from mainWindow import MainWindow
from Ui.login import Ui_MainWindow
from mysql_use import mysqlUse
import mysql_use
import generate_captcha
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QLabel, QLineEdit
import time
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QApplication
import emailCaptcha
import matplotlib
matplotlib.use('Agg')  # 在导入 pyplot 之前设置后端
import matplotlib.pyplot as plt
class LoginMainWindow(QtWidgets.QMainWindow,Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.db = mysqlUse()
        self.gs_wd = None
        self.label = self.findChild(QLabel, 'label')  # 获取QLabel 的引用
        self.user = 0
        self.captcha = ''  # 初始化验证码
        self.update_captcha()  # 初始化验证码
        self.code1 = ''
        self.code2 = ''
        self.email = ''
        self.name = ''
        self.password = ''
        self.label.mousePressEvent = self.update_captcha  # 更新图形验证码（在登录界面）
        self.pb_login.clicked.connect(self.ck_login) #点击登录按钮（在登录界面）
        self.pb_enrol.clicked.connect(self.jump_to_enrol_page)  # 点击注册按钮（在登录界面）
        self.pb_forgetPassword.clicked.connect(self.jump_to_resetPassword_page)  # 点击忘记密码按钮（在登录界面）

        self.pb_getCode.clicked.connect(self.click_pb_getCode)  # 获取验证码按钮（在重置密码界面）
        self.pb_ResetPassword.clicked.connect(self.ck_resetPassword)  # 点击重置密码按钮（在重置密码界面）
        self.pb_back.clicked.connect(self.jump_to_login_page)  # 点击返回按钮（在重置密码界面）

        self.pb_getCode2.clicked.connect(self.click_pb_getCode2)  # 获取验证码按钮（在注册界面）
        self.pb_enrol2.clicked.connect(self.ck_register)  # 点击注册按钮（在注册界面）
        self.pb_backLogin.clicked.connect(self.jump_to_login_page)  # 点击返回按钮（在注册界面）

        self.pb_completionFormation.clicked.connect(self.register_success) # 点击完善信息按钮（在完善信息界面
        self.l_password.setFocusPolicy(Qt.StrongFocus)  # 确保可以获得焦点
        # 设置初始的密码输入模式为 PasswordEchoOnEdit
        self.l_password.setEchoMode(QLineEdit.PasswordEchoOnEdit)

    def focusOutEvent(self, event):
        # 当 QLineEdit 失去焦点时，隐藏输入内容
        self.l_password.setEchoMode(QLineEdit.Password)  # 设置为密码模式，隐藏输入内容
        super().focusOutEvent(event)  # 调用基类的 focusOutEvent

    def focusInEvent(self, event):
        # 当 QLineEdit 获得焦点时，恢复输入内容
        self.l_password.setEchoMode(QLineEdit.Normal)  # 恢复正常模式
        super().focusInEvent(event)
        
    def jump_to_login_page(self):
        self.stackedWidget.setCurrentIndex(0)

    def jump_to_resetPassword_page(self):
        self.stackedWidget.setCurrentIndex(1)

    def jump_to_enrol_page(self):
        self.stackedWidget.setCurrentIndex(2)

    def jump_to_completionFormation_page(self):
        self.stackedWidget.setCurrentIndex(2)

    def update_captcha(self):
        """验证码更新"""
        img, code_str = generate_captcha.generateCaptcha()
        qimg = QImage(img.tobytes(), img.width, img.height, img.width * 3, QImage.Format_RGB888).rgbSwapped()
        pixmap = QPixmap.fromImage(qimg)
        self.label.setPixmap(pixmap)
        self.label.setPixmap(pixmap)
        # self.label.setPixmap(pixmap)
        print(f"登录验证码为: {code_str}")
        self.captcha = code_str

    def ck_login(self):
        """当登录按钮被点击时调用此方法"""
        self.l_prompt.setText("")
        user_id=self.db.login_if_exist_user(self.l_name.text(), self.l_password.text())
        if user_id:
            if self.l_code.text() == self.captcha:
                print(user_id)
                """注册成功后，跳转到功能界面"""
                self.gs_wd = MainWindow(user_id)
                self.gs_wd.show()
                self.close()
            else:
                self.l_prompt.setText("验证码错误")
        else:
            self.l_prompt.setText("账号或密码错误")

    def ck_resetPassword(self):
        """当重置密码按钮被点击时调用此方法"""
        self.l_prompt2.setText("")
        if self.l_emailCode.text() == self.code1:
            if self.validate_password(self.l_newPassword1.text()):
                if self.l_newPassword1.text() == self.l_newPassword2.text():
                    self.password = self.l_newPassword2.text()
                    print(self.email)
                    print('\n')
                    print(self.password)
                    print('right')
                    print()
                    print(self.l_email.text())
                    email = self.l_email.text()
                    new_password = self.l_newPassword2.text()
                    if email and new_password:  # 检查输入是否不为空
                        try:
                            mysql_use.mysqlUse().re_password(email, new_password)
                            self.stackedWidget.setCurrentIndex(0)
                        except Exception as e:
                            self.l_prompt2.setText(f"密码重置失败：{str(e)}")
                    else:
                        self.l_prompt2.setText("请输入有效的邮箱和密码")
                else:
                    self.l_prompt2.setText("两次密码输入不同")
            else:
                self.l_prompt2.setText("新密码格式错误（至少8个字符，包含大小写字母和数字）")
        else:
            self.l_prompt2.setText("验证码错误")

    def ck_register(self):
        """当注册账号获时注册按钮被点击时调用此方法"""
        if self.l_email2.text() == self.email:
            if self.l_emailCode2.text() == self.code2:
                print('right')
                self.stackedWidget.setCurrentIndex(3)
            else:
                self.l_prompt3.setText("验证码错误")
        else:
            self.l_prompt3.setText("验证码错误")

    def register_success(self):
        """当完善信息按钮被点击时调用此方法"""
        print("00")
        self.name = self.l_createName.text()
        self.l_prompt4.setText("")
        if self.name != "":
            print("11")
            if self.validate_password(self.l_createPassword1.text()):
                print("12")
                if self.l_createPassword1.text() == self.l_createPassword2.text():
                    print("13")
                    self.password = self.l_createPassword2.text()
                    grade=1
                    if len(self.l_grade.text())==1:
                        grade=int(self.l_grade.text())
                    print(grade)
                    mysql_use.mysqlUse().register(self.name,self.email,self.password,grade)
                    print("14")
                    self.stackedWidget.setCurrentIndex(0)
                    print("15")
                else:
                    self.l_prompt4.setText("两次密码输入不同")
            else:
                self.l_prompt4.setText("密码设置格式错误（至少8个字符，包含大小写字母和数字）")
        else:
            self.l_prompt4.setText("用户名不能为空")

    def click_pb_getCode(self):
        """当重置密码时获取邮箱验证码按钮被点击时调用此方法"""
        self.l_prompt2.setText("")
        self.email = self.l_email.text()
        if self.db.email_exit(self.email):
            code = emailCaptcha.SendEmail(self.email).send_email()
            if code:
                print(f"邮件发送成功，验证码为：{code}")
                self.code1 = code
            else:
                print("邮件发送失败")
                self.countdown()
                self.pb_getCode.setEnabled(True)
        else:
            self.l_prompt2.setText("该用户不存在，请注册")

    def click_pb_getCode2(self):
        """当注册账号时获取邮箱验证码按钮被点击时调用此方法"""
        self.l_prompt3.setText("")
        self.email = self.l_email2.text()
        if self.validate_email():
            if self.db.email_exit(self.email) != 1:
                code = emailCaptcha.SendEmail(self.email).send_email()
                if code:
                    print(f"邮件发送成功，验证码为：{code}")
                    self.code2 = code
                else:
                    print("邮件发送失败")
                # self.countdown()
                # self.pb_getCode2.setEnabled(True)
            else:
                self.l_prompt3.setText("该用户已存在")
        else:
            self.l_prompt3.setText("邮箱账号格式有误")

    def countdown(self):
        self.pushButton_7.setEnabled(False)  # 禁用按钮
        t = 60
        while t:
            timer = '倒计时{:02d}s'.format(t - 1)
            print(timer)
            self.pushButton_7.setText(timer)  # 使用倒计时字符串更新按钮文字
            self.pushButton_7.repaint()  # 强制重绘按钮
            QApplication.processEvents()  # 处理界面事件
            time.sleep(1)
            t -= 1
        self.pushButton_7.setText("重新获取")

    def countdown_6(self):
        self.pushButton_6.setEnabled(False)  # 禁用按钮
        t = 60
        while t:
            timer = '倒计时{:02d}s'.format(t)
            print(timer)
            self.pushButton_6.setText(timer)  # 使用倒计时字符串更新按钮文字
            self.pushButton_6.repaint()  # 强制重绘按钮
            QApplication.processEvents()  # 处理界面事件
            time.sleep(1)
            t -= 1
        self.pushButton_6.setText("重新获取")

    def validate_email(self):
        """邮箱格式验证"""
        pattern = r'^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$'
        if re.match(pattern, self.email):
            return True
        else:
            return False

    def validate_password(self, password):
        """密码验证格式，密码至少8个字符，包含至少一个大写字母、一个小写字母、一个数字"""
        if (len(password) >= 8 and
                re.search(r'[A-Z]', password) and
                re.search(r'[a-z]', password) and
                re.search(r'\d', password)):
            print("yes")
            return True
        else:
            print("no")
            return False

if __name__ == '__main__':
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
    app = QtWidgets.QApplication(sys.argv)
    log_wd = LoginMainWindow()
    log_wd.show()
    sys.exit(app.exec_())